package org.galaxyworld.flycode;

import com.alibaba.druid.pool.DruidDataSource;
import org.galaxyworld.flycode.config.DruidConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class FlyCodeApplication {

    @Resource
    private DruidConfig druidConfig;

    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setInitialSize(druidConfig.getInitialSize());
        druidDataSource.setMinIdle(druidConfig.getMinIdle());
        druidDataSource.setMaxActive(druidConfig.getMaxActive());
        druidDataSource.setMaxWait(druidConfig.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(druidConfig.getValidationQuery());
        druidDataSource.setTestOnBorrow(druidConfig.isTestOnBorrow());
        druidDataSource.setTestOnReturn(druidConfig.isTestOnReturn());
        druidDataSource.setTestWhileIdle(druidConfig.isTestWhileIdle());
        druidDataSource.setPoolPreparedStatements(druidConfig.isPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(druidConfig.getMaxPoolPreparedStatementPerConnectionSize());
        try {
            druidDataSource.setFilters(druidConfig.getFilters());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(FlyCodeApplication.class)
                .headless(false)
                .web(false)
                .run(args);
    }

}
